import React, { useState } from "react";
import { Card, Typography, Row, Col, Statistic, Tabs, List, Tag, Button, Space, Badge, Avatar, Input, message, Modal, Table, Progress, DatePicker } from "antd";
import { useAuth } from "../../contexts/AuthContext";
import { useNavigate } from "react-router-dom";
import { 
  UserOutlined, CalendarOutlined, DollarOutlined, SolutionOutlined, 
  CarryOutOutlined, MessageOutlined, AuditOutlined, TeamOutlined, 
  SearchOutlined, ClockCircleOutlined,
  MedicineBoxOutlined, FormOutlined, CheckCircleOutlined, AlertOutlined,
  BarChartOutlined, FileSearchOutlined
} from "@ant-design/icons";
import Layout from "../../components/Layout";
import { ROUTES } from "../../constants/routes";

const { Title } = Typography;

// Mock数据
const stats = [
  { title: "今日接诊数", value: 22, icon: <CarryOutOutlined />, color: '#007aff' },
  { title: "本月收入(元)", value: 5400, icon: <DollarOutlined />, color: '#34c759' },
  { title: "今日预约", value: 35, icon: <CalendarOutlined />, color: '#ff9500' },
  { title: "咨询消息", value: 8, icon: <MessageOutlined />, color: '#af52de' },
];

const todos = [
  { key: 'consult', label: '待处理咨询', count: 3, icon: <MessageOutlined /> },
  { key: 'report', label: '待审核报告', count: 2, icon: <AuditOutlined /> },
  { key: 'patients', label: '新患者建档', count: 1, icon: <TeamOutlined /> },
];

const appointments = [
  { id: 1, patient: '张三', time: '10:00', status: '待就诊', desc: '膝关节疼痛', gender: '男', age: 45, phone: '138****6789', appointmentType: '初诊', department: '骨科' },
  { id: 2, patient: '李四', time: '10:30', status: '已就诊', desc: '腰部不适', gender: '男', age: 38, phone: '139****5432', appointmentType: '复诊', department: '骨科' },
  { id: 3, patient: '王五', time: '11:00', status: '待就诊', desc: '康复复查', gender: '女', age: 52, phone: '137****9876', appointmentType: '随访', department: '骨科' },
  { id: 4, patient: '赵六', time: '11:30', status: '已取消', desc: '骨折随访', gender: '男', age: 28, phone: '136****4321', appointmentType: '复诊', department: '骨科' },
  { id: 5, patient: '孙七', time: '14:00', status: '待就诊', desc: '颈椎疼痛', gender: '女', age: 35, phone: '135****8765', appointmentType: '初诊', department: '骨科' },
  { id: 6, patient: '周八', time: '14:30', status: '已就诊', desc: '手腕扭伤', gender: '男', age: 42, phone: '134****3210', appointmentType: '急诊', department: '骨科' },
  { id: 7, patient: '吴九', time: '15:00', status: '待就诊', desc: '关节肿胀', gender: '女', age: 60, phone: '133****7654', appointmentType: '复诊', department: '骨科' },
  { id: 8, patient: '郑十', time: '15:30', status: '待就诊', desc: '骨折术后复查', gender: '男', age: 25, phone: '132****2109', appointmentType: '随访', department: '骨科' },
];

const shortcuts = [
  { key: 'today', icon: <CalendarOutlined />, label: '今日预约' },
  { key: 'consult', icon: <MessageOutlined />, label: '在线咨询' },
  { key: 'patient', icon: <SolutionOutlined />, label: '患者管理' },
  { key: 'analysis', icon: <AuditOutlined />, label: '报告分析' },
];

// 医生日程数据
const schedules = [
  { time: '09:00-12:00', type: '门诊', location: '门诊楼3楼骨科诊室1' },
  { time: '14:00-15:30', type: '手术', location: '住院部2楼手术室3' },
  { time: '16:00-17:00', type: '查房', location: '住院部5楼骨科病房' },
];

// 待办医嘱数据
const pendingPrescriptions = [
  { id: 1, patient: '张三', department: '骨科', doctor: '王医生', time: '10:15', urgency: '常规' },
  { id: 2, patient: '王五', department: '骨科', doctor: '王医生', time: '11:30', urgency: '紧急' },
];

// 药品库存数据
const medicineStock = [
  { id: 1, name: '布洛芬缓释胶囊', spec: '0.3g*20粒', stock: 150, threshold: 100, unit: '盒' },
  { id: 2, name: '阿莫西林胶囊', spec: '0.5g*24粒', stock: 85, threshold: 100, unit: '盒' },
  { id: 3, name: '盐酸氨基葡萄糖片', spec: '0.75g*60片', stock: 45, threshold: 50, unit: '瓶' },
];

const statusColors: Record<string, string> = {
  '待就诊': 'blue',
  '已就诊': 'green',
  '已取消': 'default',
};

const DoctorDashboard: React.FC = () => {
  const { user } = useAuth();
  const navigate = useNavigate();
  const [apptTab, setApptTab] = useState('全部');
  const [searchText, setSearchText] = useState('');
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedAppointment, setSelectedAppointment] = useState<any>(null);
  
  // 模拟医生信息
  const doctorInfo = user || {
    name: '王医生',
    department: '骨科',
    title: '主任医师',
    avatar: 'W'
  };

  const filterAppointments =
    apptTab === '全部' ? appointments : appointments.filter(a => a.status === apptTab);
  
  // 处理快捷操作点击
  const handleShortcutClick = (key: string) => {
    switch (key) {
      case 'today':
        // 今日预约已在页面中显示
        message.success('查看今日预约');
        break;
      case 'consult':
        navigate(ROUTES.doctor.consultManager);
        break;
      case 'patient':
        // 假设患者管理页面路由
        navigate('/doctor/patient-list');
        break;
      case 'analysis':
        message.info('报告分析功能开发中');
        break;
      default:
        break;
    }
  };
  
  // 查看预约详情
  const handleViewAppointment = (appointment: any) => {
    setSelectedAppointment(appointment);
    setDetailModalVisible(true);
  };
  
  // 开始接诊
  const handleStartConsultation = (appointment: any) => {
    message.success(`开始接诊患者：${appointment.patient}`);
    // 模拟状态更新
    // 实际应用中应该调用API更新状态
  };
  
  // 处理患者搜索
  const handleSearch = () => {
    if (!searchText.trim()) {
      message.info('请输入患者姓名');
      return;
    }
    // 实际应用中应该调用API搜索患者
    message.success(`搜索患者：${searchText}`);
    // 假设搜索后跳转到患者列表页面
    navigate(`/doctor/patient-list?search=${encodeURIComponent(searchText)}`);
  };

  return (
    <Layout title="医护端工作台" showBackButton={false}>
      <div className="dashboard-container">
        <div className="page-header">
          <Title level={3} className="page-title">医护端工作台</Title>
        </div>
        
        {/* 医生信息和搜索栏 */}
        <Row gutter={[16, 16]} className="dashboard-section">
          <Col xs={24} md={8}>
            <Card className="apple-card doctor-info-card">
              <Space>
                <Avatar size={64} className="doctor-avatar">{doctorInfo.avatar}</Avatar>
                <div>
                  <div className="doctor-name">{doctorInfo.name}</div>
                  <div className="doctor-title">{doctorInfo.department} | {doctorInfo.title}</div>
                </div>
              </Space>
            </Card>
          </Col>
          <Col xs={24} md={16}>
            {/* 医生专用工具栏 */}
            <Card 
              title="医生工作区" 
              className="apple-card tool-card"
              extra={
                <Space>
                  <DatePicker className="date-picker" />
                  <Button type="primary" icon={<FileSearchOutlined />} className="apple-button">统计查询</Button>
                </Space>
              }
            >
              <Row gutter={16}>
                <Col span={6}>
                  <Button 
                    type="primary" 
                    size="large" 
                    block
                    icon={<MedicineBoxOutlined />}
                    onClick={() => navigate('/doctor/pharmacy')}
                    className="workspace-button"
                  >
                    药品管理
                  </Button>
                </Col>
                <Col span={6}>
                  <Button 
                    type="primary" 
                    size="large" 
                    block
                    icon={<BarChartOutlined />}
                    onClick={() => navigate('/doctor/statistics')}
                    className="workspace-button"
                  >
                    业绩统计
                  </Button>
                </Col>
                <Col span={6}>
                  <Button 
                    type="primary" 
                    size="large" 
                    block
                    icon={<CheckCircleOutlined />}
                    onClick={() => navigate('/doctor/examination')}
                    className="workspace-button"
                  >
                    检查申请
                  </Button>
                </Col>
                <Col span={6}>
                  <Button 
                    type="primary" 
                    size="large" 
                    block
                    icon={<AlertOutlined />}
                    onClick={() => navigate('/doctor/emergency')}
                    className="workspace-button"
                  >
                    急诊处理
                  </Button>
                </Col>
              </Row>
            </Card>
            <Card className="apple-card search-card">
              <Space className="search-container">
                <Input
                  placeholder="搜索患者姓名"
                  value={searchText}
                  onChange={(e) => setSearchText(e.target.value)}
                  className="search-input"
                  prefix={<SearchOutlined />}
                  onPressEnter={handleSearch}
                />
                <Button type="primary" onClick={handleSearch} className="apple-button">搜索</Button>
                <Button onClick={() => navigate(ROUTES.doctor.emrList)} className="apple-button-secondary">病历管理</Button>
              </Space>
            </Card>
          </Col>
        </Row>
        
        {/* 统计数据 */}
        <Row gutter={[16, 16]} className="dashboard-section">
          {stats.map((stat, idx) => (
            <Col xs={12} sm={6} key={stat.title}>
              <Card className="apple-card stat-card">
                <Space>
                  <span className="stat-icon" style={{ fontSize: 22, color: stat.color }}>{stat.icon}</span>
                  <Statistic title={stat.title} value={stat.value} className="stat-item" />
                </Space>
              </Card>
            </Col>
          ))}
        </Row>
        
        <Row gutter={[16, 16]} className="dashboard-main">
          <Col xs={24} md={8} className="sidebar-col">
            {/* 待办 */}
            <Card title="待办事项" className="apple-card todo-card">
              <List
                dataSource={todos}
                renderItem={item => (
                  <List.Item className="todo-item">
                    <List.Item.Meta
                      avatar={item.icon}
                      title={<>{item.label}</>}
                    />
                    <Badge count={item.count} offset={[10, 0]} className="todo-badge" />
                  </List.Item>
                )}
              />
            </Card>
            
            {/* 快捷操作 */}
            <Card title="快捷操作" className="apple-card shortcuts-card">
              <Space wrap className="shortcuts-container">
                {shortcuts.map(sc => (
                  <Button 
                    icon={sc.icon} 
                    key={sc.key} 
                    size="large" 
                    type="default" 
                    shape="round" 
                    onClick={() => handleShortcutClick(sc.key)}
                    className="shortcut-button"
                  >
                    {sc.label}
                  </Button>
                ))}
              </Space>
            </Card>
            
            {/* 药品库存预警 */}
            <Card 
              title="药品库存" 
              icon={<MedicineBoxOutlined />}
              className="apple-card stock-card"
            >
              <Table 
                dataSource={medicineStock} 
                pagination={false} 
                size="small"
                className="stock-table"
                columns={[
                  {
                    title: '药品名称',
                    dataIndex: 'name',
                    key: 'name',
                  },
                  {
                    title: '规格',
                    dataIndex: 'spec',
                    key: 'spec',
                    width: 80,
                    render: text => <span className="spec-text">{text}</span>,
                  },
                  {
                    title: '库存',
                    dataIndex: ['stock', 'unit'],
                    key: 'stock',
                    render: (value, record) => (
                      <div className="stock-info">
                        <div className="stock-value">{record.stock} {record.unit}</div>
                        <Progress 
                          percent={(record.stock / record.threshold) * 100} 
                          strokeColor={{
                            '0%': '#007aff',
                            '100%': record.stock < record.threshold ? '#ff3b30' : '#34c759',
                          }}
                          size="small"
                          className="stock-progress"
                        />
                      </div>
                    ),
                  },
                ]}
              />
            </Card>
          </Col>

          <Col xs={24} md={16} className="main-content-col">
            {/* 今日预约 */}
            <Card
              title="今日预约列表"
              tabList={[{ key: '全部', tab: '全部' }, { key: '待就诊', tab: '待就诊' }, { key: '已就诊', tab: '已就诊' }, { key: '已取消', tab: '已取消' }]}
              activeTabKey={apptTab}
              onTabChange={setApptTab as any}
              className="apple-card appointments-card"
            >
              <List
                itemLayout="horizontal"
                dataSource={filterAppointments}
                locale={{ emptyText: '无预约' }}
                pagination={{ pageSize: 5 }}
                renderItem={item => (
                  <List.Item 
                    className="appointment-item"
                    actions={[
                      item.status === '待就诊' && (
                        <Button 
                          type="primary" 
                          size="small" 
                          key="start"
                          onClick={() => handleStartConsultation(item)}
                          className="apple-button-small"
                        >
                          开始接诊
                        </Button>
                      ),
                      <Button 
                        size="small" 
                        key="detail"
                        onClick={() => handleViewAppointment(item)}
                        className="apple-button-small-secondary"
                      >
                        详情
                      </Button>,
                      <Button 
                        size="small" 
                        key="emr"
                        onClick={() => navigate(`/doctor/patient/${item.id}`)}
                        className="apple-button-small-secondary"
                      >
                        查看病历
                      </Button>,
                      item.status === '待就诊' && (
                        <Button 
                          danger 
                          size="small" 
                          key="cancel"
                          onClick={() => {
                            message.success(`已取消患者${item.patient}的预约`);
                          }}
                          className="apple-button-small-danger"
                        >
                          取消预约
                        </Button>
                      )
                    ].filter(Boolean)}
                  >
                    <List.Item.Meta
                      avatar={<Avatar icon={<UserOutlined />} className="patient-avatar" />}
                      title={
                        <div className="patient-title">
                          <Space>
                            <span className="patient-name">{item.patient}</span>
                            <Tag color={statusColors[item.status]} className="status-tag">{item.status}</Tag>
                            <Tag color={item.appointmentType === '初诊' ? 'blue' : 
                                       item.appointmentType === '复诊' ? 'green' : 
                                       item.appointmentType === '急诊' ? 'red' : 'orange'}
                                 className="appointment-type-tag">
                              {item.appointmentType}
                            </Tag>
                          </Space>
                        </div>
                      }
                      description={
                        <div className="patient-info">
                          <div className="patient-basic-info">时间：{item.time} &nbsp;&nbsp;性别：{item.gender} &nbsp;&nbsp;年龄：{item.age}岁</div>
                          <div className="patient-symptom">症状：{item.desc}</div>
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
            
            {/* 医生日程 */}
            <Card 
              title="今日日程安排" 
              icon={<ClockCircleOutlined />}
              className="apple-card schedule-card"
            >
              <List
                dataSource={schedules}
                renderItem={(item, index) => (
                  <List.Item className="schedule-item">
                    <List.Item.Meta
                      title={
                        <div className="schedule-title">
                          <strong>{item.time}</strong> - {item.type}
                          <Tag color={
                            item.type === '门诊' ? 'blue' : 
                            item.type === '手术' ? 'red' : 'green'
                          } className="schedule-type-tag">
                            {item.type}
                          </Tag>
                        </div>
                      }
                      description={
                        <div className="schedule-location">
                          地点：{item.location}
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
            
            {/* 待办医嘱 */}
            <Card 
              title="待办医嘱" 
              icon={<FormOutlined />}
              className="apple-card prescription-card"
            >
              <List
                dataSource={pendingPrescriptions}
                renderItem={(item) => (
                  <List.Item
                    className="prescription-item"
                    actions={[
                      <Button 
                        type="primary" 
                        size="small"
                        onClick={() => message.success(`已处理患者${item.patient}的医嘱`)} 
                        className="apple-button-small"
                      >
                        处理
                      </Button>
                    ]}
                  >
                    <List.Item.Meta
                      title={
                        <div className="prescription-title">
                          {item.patient}
                          <Tag color={item.urgency === '紧急' ? 'red' : 'blue'} className="urgency-tag">
                            {item.urgency}
                          </Tag>
                        </div>
                      }
                      description={
                        <div className="prescription-info">
                          时间：{item.time}，科室：{item.department}
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
          </Col>
        </Row>
      </div>
      
      {/* 预约详情模态框 */}
      <Modal
        title="预约详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={600}
        className="apple-modal"
      >
        {selectedAppointment && (
          <div className="modal-content">
            <div className="modal-header">
              <div className="modal-title">
                {selectedAppointment.patient} <Tag color={statusColors[selectedAppointment.status]} className="status-tag">
                  {selectedAppointment.status}
                </Tag>
              </div>
            </div>
            
            <Row gutter={[16, 16]} className="modal-section">
              <Col span={12}>
                <Card title="基本信息" className="apple-card modal-card">
                  <div className="modal-info">
                    <div><strong>预约时间：</strong>{selectedAppointment.time}</div>
                    <div><strong>预约类型：</strong>
                      <Tag color={selectedAppointment.appointmentType === '初诊' ? 'blue' : 
                                 selectedAppointment.appointmentType === '复诊' ? 'green' : 
                                 selectedAppointment.appointmentType === '急诊' ? 'red' : 'orange'}
                           className="appointment-type-tag">
                        {selectedAppointment.appointmentType}
                      </Tag>
                    </div>
                    <div><strong>预约科室：</strong>{selectedAppointment.department}</div>
                    <div><strong>预约医生：</strong>{doctorInfo.name}</div>
                  </div>
                </Card>
              </Col>
              <Col span={12}>
                <Card title="患者信息" className="apple-card modal-card">
                  <div className="modal-info">
                    <div><strong>患者性别：</strong>{selectedAppointment.gender}</div>
                    <div><strong>患者年龄：</strong>{selectedAppointment.age}岁</div>
                    <div><strong>患者电话：</strong>{selectedAppointment.phone}</div>
                    <div><strong>就诊编号：</strong>PT-{selectedAppointment.id}-{new Date().getFullYear()}</div>
                  </div>
                </Card>
              </Col>
            </Row>
            
            <Card title="症状描述" className="apple-card modal-card">
              <div className="symptom-description">
                {selectedAppointment.desc}
              </div>
            </Card>
            
            <Card title="历史就诊" className="apple-card modal-card">
              <List
                size="small"
                bordered
                dataSource={[
                  { key: '1', date: '2024-01-15', doctor: '王医生', desc: '初步诊断为膝关节退行性病变' },
                  { key: '2', date: '2024-01-20', doctor: '王医生', desc: '复查，调整治疗方案' },
                ]}
                className="history-list"
                renderItem={item => (
                  <List.Item className="history-item">
                    <List.Item.Meta
                      title={item.date}
                      description={
                        <>
                          <div>医生：{item.doctor}</div>
                          <div>就诊记录：{item.desc}</div>
                        </>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
            
            <Space className="modal-actions">
              {selectedAppointment.status === '待就诊' && (
                <>
                  <Button 
                    danger 
                    onClick={() => {
                      message.success(`已取消患者${selectedAppointment.patient}的预约`);
                      setDetailModalVisible(false);
                    }}
                    className="apple-button-danger"
                  >
                    取消预约
                  </Button>
                  <Button 
                    type="primary" 
                    onClick={() => {
                      handleStartConsultation(selectedAppointment);
                      setDetailModalVisible(false);
                    }}
                    className="apple-button"
                  >
                    开始接诊
                  </Button>
                </>
              )}
              <Button onClick={() => setDetailModalVisible(false)} className="apple-button-secondary">关闭</Button>
            </Space>
          </div>
        )}
      </Modal>
    </Layout>
  );
};
export default DoctorDashboard;


